package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;
import cn.com.winning.ecare.common.AsyncImageLoader;
import cn.com.winning.ecare.common.Grideviewmenu;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.SlidingLayout;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**医院信息主界面
 * @author Administrator
 *
 */
public class HospitalOne extends TabActivity
{

	TabHost tabHost;
	private TabWidget mTabWidget;

	private TextView tv_hosName = null; // 医院名称
	private ImageView iv_hosImg = null;// 医院图片
	private TextView tv_hosDj = null; // 医院等级

	private CustomProgressDialog proDialog;// 加载框
	private HospitalOne oThis = this;

	private String strName, strInfo, strId, strPic, strDj,imgname;
	private Bitmap bitmap;

	/**
	 * 侧滑布局对象，用于通过手指滑动将左侧的菜单布局进行显示或隐藏。
	 */
	private SlidingLayout slidingLayout;

	private LinearLayout content;

	/**
	 * menu按钮，点击按钮展示左侧布局，再点击一次隐藏左侧布局。
	 */
	private ImageButton menuButton;

	private GridView gridView;
	Grideviewmenu gm;
	private TextView nametv, tv;
	MyApplication myApp;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.hospital_one);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
//		myApp.getUserRecords().setUsername(myApp.getAccount());
//		myApp.getUserRecords().setModule("HospitalOne@医院信息");
//		UserRecord.getInstance(myApp.getUserRecords()).init();
		// 设置滑动菜单
		initSliding();

		// 找到相应控件
		findView();

		// 获取初始化数据
		getData();
		
		

	}

	private void initSliding()
	{
		// slidingLayout = (SlidingLayout) findViewById(R.id.slidingLayout);
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		// content = (LinearLayout) findViewById(R.id.content);
		// 将监听滑动事件绑定在contentListView上
		// slidingLayout.setScrollEvent(content);
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// if (slidingLayout.isLeftLayoutVisible()) {
				// slidingLayout.scrollToRightLayout();
				// } else {
				// slidingLayout.scrollToLeftLayout();
				// }
				oThis.onBackPressed();
			}
		});
		// gm = new Grideviewmenu();
		// gridView = (GridView) findViewById(R.id.hgridview_menu);
		// // 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
		// SimpleAdapter adapter = new SimpleAdapter(this, gethData(), // 数据来源
		// R.layout.grideview_menulist,// XML实现
		// new String[] { "ItemImage", "ItemText" }, // 动态数组与ImageItem对应的子项
		// new int[] { R.id.gridviewmenu_imageview, R.id.gridviewmenu_textview }//
		// //ImageItem的XML文件里面的一个ImageView,两个TextView
		// // ID
		// );
		// // 添加并且显示
		// gridView.setAdapter(adapter);
		// // 添加消息处理
		// gridView.setOnItemClickListener(clickListener);
		// nametv = (TextView)findViewById(R.id.husername_menu);
		// MyApplication myapp=(MyApplication)getApplication();
		// nametv.setText(myapp.getHzxm());
		// tv = (TextView)findViewById(R.id.hout_menu);
		//
		// //滑动菜单里面退出按钮
		// tv.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// finish();
		// Intent intent = new Intent();
		// intent.setClass(oThis, Login.class);
		// startActivity(intent);
		// }
		// });
		

	}

	private void iniTabHost()
	{
		MyApplication myApplication = (MyApplication) getApplication();
		myApplication.setYycontent(strInfo);
		Intent intent1 = new Intent();
		intent1.setClass(this, Hospitalcontent.class);

		Intent intent2 = new Intent();
		intent2.putExtra("strId", strId);
		intent2.setClass(this, HospitalTwo.class);

		// 新建一个tab并设置它的，Tag,标题，图标，内容
		tabHost.addTab(tabHost.newTabSpec("详情").setIndicator("详情").setContent(intent1));
		tabHost.addTab(tabHost.newTabSpec("科室").setIndicator("科室").setContent(intent2));
		tabHost.setCurrentTab(0);// 设置初始选中状态为第一个tab
		// 初始化TabHost
		for (int i = 0; i < mTabWidget.getChildCount(); i++)
		{
			RelativeLayout view = (RelativeLayout) mTabWidget.getChildAt(i);

			TextView text = (TextView) view.findViewById(android.R.id.title);
			text.setTextSize(18);
			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) text.getLayoutParams();
			params.width = RelativeLayout.LayoutParams.MATCH_PARENT;
			params.height = RelativeLayout.LayoutParams.MATCH_PARENT;
			text.setLayoutParams(params);
			text.setGravity(Gravity.CENTER);
			view.setBackgroundColor(getResources().getColor(R.color.color_white));
			if (tabHost.getCurrentTab() == i)
			{
				text.setTextColor(getResources().getColor(R.color.listheadtext_color));

			}
			else
			{
				text.setTextColor(getResources().getColor(R.color.test_color_register));
			}
			int heightPx = DisplayUtil.dip2px(this, 50);
			mTabWidget.getChildAt(i).getLayoutParams().height = heightPx;
		}
		// TabHost切换
		tabHost.setOnTabChangedListener(new OnTabChangeListener()
		{

			public void onTabChanged(String tabId)
			{
				// TODO Auto-generated method stub
				for (int i = 0; i < mTabWidget.getChildCount(); i++)
				{
					View view = mTabWidget.getChildAt(i);
					TextView text = (TextView) view.findViewById(android.R.id.title);
					if (tabHost.getCurrentTab() == i)
					{
						text.setTextColor(getResources().getColor(R.color.listheadtext_color));
					}
					else
					{
						text.setTextColor(getResources().getColor(R.color.test_color_register));
					}
				}
			}

		});
	}

	private void getData()
	{
		proDialog = CustomProgressDialog.createDialog(this);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			iniHosName();
			Looper.loop();
		}
	}

	private void iniHosName()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			Bundle bundle = new Bundle();
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("id", "0"));

			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.HOSPITALNAME, ls);

			if (json != null && !json.equals(""))
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (!json.getString("nodeinfo").equals("") && !json.getString("nodeinfo").equals("[]"))
					{
						// 获取收费信息
						JSONArray jsonArr = new JSONArray(json.getString("nodeinfo"));
						JSONObject js = jsonArr.getJSONObject(0);
						strName = js.getString("orgname");
						strId = js.getString("id");
						strInfo = js.getString("sxnr");
						strDj = js.getString("grade");
						imgname = js.getString("imgpath");
						// 获取图片
//						List<NameValuePair> ls1 = new ArrayList<NameValuePair>();
//						ls1.add(new BasicNameValuePair("id", strId));
//						bitmap = HTTPGetTool.getTool().queryByteForPost(URLUtils.HOST + URLUtils.HOSPITALPIC, ls1);
						
						AsyncImageLoader imageLoader = new AsyncImageLoader(getApplicationContext());
						bitmap = imageLoader.loadImageS(imgname,URLUtils.HOST + URLUtils.HOSPITALPICMAIN);
						
						bundle.putInt("type", 0);
						bundle.putString("msg", "");
					}
					else
					{
						bundle.putInt("type", -1);
						bundle.putString("msg", "暂无数据");
					}

				}
				else
				{
					bundle.putInt("type", -1);
					bundle.putString("msg", "系统错误");
				}

			}
			else
			{
				bundle.putInt("type", -1);
				bundle.putString("msg", "网络连接失败!");
			}
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 捕捉异常
			Bundle bundle = new Bundle();
			bundle.putInt("type", -1);
			bundle.putString("msg", e.toString());
			Message msg = myHandler.obtainMessage();
			msg.setData(bundle);
			myHandler.sendMessage(msg);
		}

	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			int type = msg.getData().getInt("type");
			switch (type)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
					break;
				case 0:
					proDialog.dismiss();
					setName();
					iniTabHost();
					break;
				case 1:
					proDialog.dismiss();
					// setHosInfo();
					break;

				default:
					break;
			}
		};
	};

	
	private void findView()
	{
		tv_hosName = (TextView) this.findViewById(R.id.hos_name);
		iv_hosImg = (ImageView) this.findViewById(R.id.hos_img);
		tv_hosDj = (TextView) this.findViewById(R.id.hos_dj);
		oThis = this;
		tabHost = getTabHost();
		mTabWidget = (TabWidget) this.findViewById(android.R.id.tabs);

	}
	private void setName()
	{
		tv_hosName.setText(strName);
		tv_hosDj.setText(strDj);
		// 加载图片
		if (bitmap != null)
			iv_hosImg.setImageBitmap(bitmap);
	}

	// 获取GrideView数据
	// private ArrayList<HashMap<String, Object>> gethData() {
	// MyApplication myApplication = (MyApplication) getApplication();
	// return gm.initItem(myApplication);//初始化GrideView
	// }
	// // 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
	// private OnItemClickListener clickListener = new OnItemClickListener() {
	//
	// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
	// long arg3) {
	// if (slidingLayout.isLeftLayoutVisible()) {//如果滑动菜单隐藏，屏蔽点击事件
	// Intent intent = null;
	// HashMap<String, Object> Item = (HashMap<String, Object>) arg0
	// .getItemAtPosition(arg2);
	// intent = gm.findActivity(intent,Item, oThis);
	// startActivity(intent);
	// oThis.finish();
	// }
	// }
	// };

}
